const fs = require('fs');
const path = require('path');

// 需要修复的页面目录
const pageDirs = [
  'pages/service',
  'pages/user',
  'pages/village',
  'pages/admin',
  'pages/auth',
  'pages/common',
  'pages/activity'
];

// 需要修复的文件模式
const filePatterns = [
  'index.js',
  'profile/index.js',
  'apply/index.js',
  'detail/index.js'
];

// 修复函数
function fixLoadingState(filePath) {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let modified = false;

    // 修复1: 移除onReady中的重复hideGlobalLoading调用
    const onReadyPattern = /onReady\(\)\s*\{[\s\S]*?setTimeout\(\(\)\s*=>\s*\{[\s\S]*?this\.hideGlobalLoading\(\)[\s\S]*?\},?\s*\d+\)[\s\S]*?pageLoadingManager\.onPageDataLoaded\([^)]+\)[\s\S]*?\}/g;
    if (onReadyPattern.test(content)) {
      content = content.replace(onReadyPattern, (match) => {
        // 提取pageLoadingManager.onPageDataLoaded调用
        const pageDataLoadedMatch = match.match(/pageLoadingManager\.onPageDataLoaded\([^)]+\)/);
        if (pageDataLoadedMatch) {
          modified = true;
          return `onReady() {
    // 页面准备完成，隐藏加载效果
    ${pageDataLoadedMatch[0]}
  },`;
        }
        return match;
      });
    }

    // 修复2: 确保数据加载完成后调用hideGlobalLoading
    // 查找async方法中的数据处理逻辑
    const asyncMethodPattern = /(async\s+\w+\([^)]*\)\s*\{[\s\S]*?)(this\.setData\(\{[^}]*loading:\s*false[^}]*\}\);?)([\s\S]*?)(wx\.hideLoading\(\);?)([\s\S]*?\})/g;
    content = content.replace(asyncMethodPattern, (match, before, setData, middle, hideLoading, after) => {
      // 如果已经有hideGlobalLoading调用，跳过
      if (match.includes('this.hideGlobalLoading()')) {
        return match;
      }
      
      modified = true;
      return before + setData + middle + '        // 数据加载完成，隐藏全局加载\n        this.hideGlobalLoading();\n        ' + hideLoading + after;
    });

    // 修复3: 在错误处理中也添加hideGlobalLoading
    const errorPattern = /(catch\s*\([^)]*\)\s*\{[\s\S]*?console\.error\([^;]*\);?[\s\S]*?)(wx\.hideLoading\(\);?)([\s\S]*?\})/g;
    content = content.replace(errorPattern, (match, before, hideLoading, after) => {
      if (match.includes('this.hideGlobalLoading()')) {
        return match;
      }
      
      modified = true;
      return before + '      this.hideGlobalLoading();\n      ' + hideLoading + after;
    });

    // 修复4: 移除wx.showLoading和wx.hideLoading的重复调用
    // 如果页面使用了全局加载，就不需要再使用wx.showLoading
    if (content.includes('showGlobalLoading') && content.includes('wx.showLoading')) {
      content = content.replace(/wx\.showLoading\(\{[^}]*\}\);?\s*/g, '');
      content = content.replace(/wx\.hideLoading\(\);?\s*/g, '');
      modified = true;
    }

    if (modified) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`✅ 已修复: ${filePath}`);
      return true;
    } else {
      console.log(`⏭️  无需修复: ${filePath}`);
      return false;
    }
  } catch (error) {
    console.error(`❌ 修复失败: ${filePath}`, error.message);
    return false;
  }
}

// 递归查找文件
function findFiles(dir, patterns) {
  const files = [];
  
  function traverse(currentDir) {
    try {
      const items = fs.readdirSync(currentDir);
      
      for (const item of items) {
        const fullPath = path.join(currentDir, item);
        const stat = fs.statSync(fullPath);
        
        if (stat.isDirectory()) {
          traverse(fullPath);
        } else if (stat.isFile() && patterns.some(pattern => item === pattern)) {
          files.push(fullPath);
        }
      }
    } catch (error) {
      console.warn(`⚠️  无法访问目录: ${currentDir}`, error.message);
    }
  }
  
  traverse(dir);
  return files;
}

// 主函数
function main() {
  console.log('🔧 开始修复加载状态问题...\n');
  
  let totalFixed = 0;
  let totalSkipped = 0;
  
  for (const pageDir of pageDirs) {
    const fullPath = path.join(__dirname, '..', pageDir);
    
    if (!fs.existsSync(fullPath)) {
      console.log(`⚠️  目录不存在: ${fullPath}`);
      continue;
    }
    
    console.log(`📁 处理目录: ${pageDir}`);
    
    const files = findFiles(fullPath, filePatterns);
    
    for (const file of files) {
      const relativePath = path.relative(path.join(__dirname, '..'), file);
      
      if (fixLoadingState(file)) {
        totalFixed++;
      } else {
        totalSkipped++;
      }
    }
    
    console.log('');
  }
  
  console.log('🎉 修复完成!');
  console.log(`✅ 已修复: ${totalFixed} 个文件`);
  console.log(`⏭️  跳过: ${totalSkipped} 个文件`);
}

// 运行脚本
if (require.main === module) {
  main();
}

module.exports = { fixLoadingState, findFiles };
